package com.example.filemanager;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;


import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Layout;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends Activity implements OnClickListener{
	private ListView listview_fileList;
	private Button back;
	private Button test;
	private TextView noSDcard;
	private List<String> fileList0;
	public static List<Map<String, Object>> fileList;
	FileListAdapter adapter;
	String parentPath;
	String currentPath;
	
	OpenFile openFile;
	
	boolean ISCOPY = false;
	boolean ISCUP = false;
	
	String oldFilePath = "";
	
	//长按目录ID
	final int menu_delete = 0;
	final int menu_rename = 1;
	final int menu_copy = 2;
//	final int menu_property= 3;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		listview_fileList = (ListView) findViewById(R.id.main_listview_filelist);
		back =(Button) findViewById(R.id.main_btn_back);
		back.setOnClickListener(this);
		test = (Button) findViewById(R.id.main_btn_test);
		test.setOnClickListener(this);
		noSDcard = (TextView) findViewById(R.id.main_txv_noSDcard);
		
		if(Manager.SDcardExist()){
			noSDcard.setVisibility(View.GONE);
			listview_fileList.setVisibility(View.VISIBLE);
			File SDcardROOT = Manager.getSDcardROOT();//获取SD卡根目录
			currentPath = SDcardROOT.getAbsolutePath();
			showFile(SDcardROOT);
		}else{
			noSDcard.setVisibility(View.VISIBLE);
			listview_fileList.setVisibility(View.GONE);
		}
		
		/**
		 * 列表点击
		 */
		listview_fileList.setOnItemClickListener(new ListView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				String filePath = (String) fileList.get(arg2).get("filepath");
				File file = new File(filePath);
				showFile(file);
			}
		});
		
		listview_fileList.setLongClickable(true);		
		/**
		 * 列表长按
		 */
		listview_fileList.setOnCreateContextMenuListener(new ListView.OnCreateContextMenuListener() {
			
			@Override
			public void onCreateContextMenu(ContextMenu menu, View v,
					ContextMenuInfo menuInfo) {
				menu.setHeaderTitle("选项");      
                menu.add(0, menu_delete, 0, "删除");   
                menu.add(0, menu_rename, 0, "重命名"); 
                menu.add(0, menu_copy, 0, "复制"); 
//                menu.add(0, menu_property, 0, "属性"); 
                
			}
		});
	}
	
	
	/**
	 * 列表长按监听
	 */
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		int itemId = item.getItemId();
		//获取当前点击的items
		AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
		int position = menuInfo.position;
		String fileName = (String) fileList.get(position).get("filename");
		
		switch (itemId) {
		case menu_delete:
			delete(fileName);
			break;
		case menu_rename:
//			Toast.makeText( this, "重命名", Toast.LENGTH_SHORT).show();
			rename(fileName);
			break;
		case menu_copy:
			copy(fileName);
			break;
//		case menu_property:
//			File file = new File(currentPath+"/"+fileName);
//			checkProperty(file);
//			break;
		default:
			break;
		}
		
		
//		if(itemId == menu_delete){
//			AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
//			int position = menuInfo.position;
//			String fileName = (String) fileList.get(position).get("filename");
//			delete(fileName);
//		}
//		else if(itemId == menu_delete){
//			
//		}
		
		return super.onContextItemSelected(item);
	}
	
	/**
	 * 刷新当前界面
	 */
	public  void refresh() {
		showFile(new File(currentPath));
	}
	
	
	/**
	 * 显示文件列表
	 */
	private void showFile(File filePath) {
		if(filePath.isDirectory()){
			fileList = Manager.getData(filePath);//
			if(adapter == null){
				adapter = new FileListAdapter( this, fileList);
				listview_fileList.setAdapter(adapter);
			}else{
				adapter.resetData(fileList);
			}
			adapter.notifyDataSetChanged();
			parentPath = filePath.getParent();
			currentPath = filePath.getPath();
			System.out.println("currentPath: "+ currentPath);
			System.out.println("parentPath: "+ parentPath);
		}else{
//			Toast.makeText(this, "当前只能打开文件夹", Toast.LENGTH_SHORT).show();
			if(openFile == null){
				openFile = new OpenFile(this);
			}
			openFile.openFile(filePath);//调用对应应用打开文件
		}
		
	}


	@Override
	public void onClick(View v) {
		int vid = v.getId();
		switch (vid) {
		case R.id.main_btn_back:
			boolean isRootPath = Manager.isRootPath(currentPath);
			if(isRootPath){
				Toast.makeText( this, "当前已经是根目录了", Toast.LENGTH_SHORT).show();
			}else{
				File file = new File(parentPath);
				showFile(file);
			}
			break;

		case R.id.main_btn_test:
//			FileType.isAudioFileType("/mnt/sdcard/001.mp3");
//			FileType.checkFileType(currentPath+"/camera.jpg");
			openOptionsMenu();
			
			break;
			
		default:
			break;
		}
	}
	/**
	 * 创建menu菜单
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	/**
	 * 监听menu菜单
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {
		case R.id.menu_new: //新建文件夹
			creatDirDialog();
			break;
		case R.id.menu_paste:
			paste();
			break;
		case R.id.menu_about:
			Toast.makeText( this, "关于", Toast.LENGTH_SHORT).show();
			break;

		default:
			return super.onOptionsItemSelected(item);
		}
		return true;
		
	}
	
	/**
	 * 新建文件夹对话框
	 */
	
	private void creatDirDialog() {
		AlertDialog.Builder builder;
    	final AlertDialog alertDialog;
    	
    	LayoutInflater inflater = LayoutInflater.from(this);
    	View layout  = inflater.inflate(R.layout.creat_dir_layout , null);
    	final EditText edt_name = (EditText) layout.findViewById(R.id.creat_dir_edt_name);
    	
    	
    	builder = new AlertDialog.Builder(this);
    	builder.setView(layout);
    	builder.setTitle("新建文件夹");
    	builder.setPositiveButton("建立", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String dirName = edt_name.getText().toString();
				if(dirName == null || dirName.equals("")){
					Toast.makeText(MainActivity.this, "请输入文件夹名称", Toast.LENGTH_SHORT).show();
					dialog.cancel();
					return;
				}
				if(Manager.isRename(dirName)){
					Toast.makeText(MainActivity.this, "当前已经有 \"" +dirName + "\"文件夹", Toast.LENGTH_SHORT).show();
					dialog.cancel();
					return;
				}
				
		    	String filePath  = currentPath +"/"+ dirName;
		    	if(Manager.makeNewDir(filePath) == null){
		    		Toast.makeText( MainActivity.this, "新建文件夹失败", Toast.LENGTH_SHORT).show();
		    	}else{
		    		refresh();
		    	}
		    	dialog.cancel();
			}
		});
    	
    	builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
    	alertDialog = builder.create();
    	alertDialog.show();
	}
	
	/**
	 * 删除文件
	 * @param fileName
	 */
	private void delete(final String fileName) {
		AlertDialog.Builder builder = new Builder(MainActivity.this);
		builder.setTitle("删除提示！");
		builder.setMessage("您确定要删除\"" + fileName+"\"吗？");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if(Manager.delFile(currentPath, fileName)){
					refresh();
				}else{
					Toast.makeText( MainActivity.this, "删除失败" , Toast.LENGTH_SHORT).show();
				}
				dialog.dismiss();
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		
		builder.create().show();
	}
	/**
	 * 重命名
	 * @param oldName
	 */
	private void rename(final String oldName) {
		AlertDialog.Builder builder = new Builder(this);
		LayoutInflater inflater = LayoutInflater.from(this);
		View layout = inflater.inflate( R.layout.rename_dialog_layout, null);
		final EditText edt_newName = (EditText) layout.findViewById(R.id.edt_rename_newname);
		edt_newName.setHint(oldName);
		
		builder.setTitle("重命名");
		builder.setView(layout);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				final String newName = edt_newName.getText().toString();
				if( newName == null || newName.equals("")){
					Toast.makeText(MainActivity.this, "请输入文件名", Toast.LENGTH_SHORT).show();
				}
				else{
					if(!(Manager.doRename(currentPath, oldName, newName))){
						Toast.makeText(MainActivity.this, "操作失败", Toast.LENGTH_SHORT).show();
					}
				}
				refresh();
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
	}
	/**
	 * 复制
	 */
	private void copy(String fileName) {
		oldFilePath = currentPath+"/"+fileName;
		ISCOPY = true;
	}
	
	/**
	 * 粘贴
	 */
	private void paste() {
		if(!ISCOPY){
			Toast.makeText( this, "请先复制（剪切）", Toast.LENGTH_SHORT).show();
			return;
		}
		if(new File(oldFilePath).isDirectory()){//文件夹还不能复制
			//复制文件夹
			try {
				if(!(Manager.copyDirectiory( oldFilePath, currentPath+"/"+ new File(oldFilePath).getName()))){
					Toast.makeText( this, "无法粘贴", Toast.LENGTH_SHORT).show();
				}
				refresh();
			} catch (IOException e) {
				e.printStackTrace();
//				ISCOPY = false;
			}
			refresh();
		}else{
			try {
				//复制单个文件
					if(!(Manager.copyFile( new File(oldFilePath), new File(currentPath+"/"+ new File(oldFilePath).getName())))){
						Toast.makeText( this, "无法粘贴", Toast.LENGTH_SHORT).show();
					}
					refresh();
				} catch (IOException e) {
					e.printStackTrace();
					ISCOPY = false;
				}
		}
	}
	
	/**
	 * 查看属性
	 */
	private void checkProperty(File file) {
		Map<String, Object> map = Manager.checkProperty(file);
		LayoutInflater inflater = LayoutInflater.from(this);
		View layout = inflater.inflate( R.layout.file_property_layout, null);
		
		TextView filename = (TextView) layout.findViewById(R.id.propety_txv_filename);
		TextView filepath = (TextView) layout.findViewById(R.id.propety_txv_filepath);
		TextView filesize = (TextView) layout.findViewById(R.id.propety_txv_filesize);
		TextView time = (TextView) layout.findViewById(R.id.propety_txv_time);
		TextView can_read = (TextView) layout.findViewById(R.id.propety_txv_can_read);
		TextView can_write = (TextView) layout.findViewById(R.id.propety_txv_can_write);
		TextView is_hide = (TextView) layout.findViewById(R.id.propety_txv_is_hide);
		
		
		long fileSize = file.length();
		String filePath = file.getPath();
		long modifyTime = file.lastModified();//最后修改时间
		boolean canRead = file.canRead();//是否可读
		boolean canWrite = file.canWrite();//是否可写
		boolean isHide = file.isHidden();//是否隐藏
		

	}
	
	
	
	/**
	 * 返回键监听
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		   
        if (keyCode == KeyEvent.KEYCODE_BACK
                  && event.getRepeatCount() == 0) {
        	boolean isRootPath = Manager.isRootPath(currentPath);
			if(isRootPath){
				AlertDialog.Builder builder = new Builder(this);
				builder.setTitle("退出提示");
				builder.setMessage("要退出文件管理吗?");
				builder.setPositiveButton("退出", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						MainActivity.this.finish();
					}
				});
				builder.setNegativeButton( "取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
				builder.create().show();
			}else{
				File file = new File(parentPath);
				showFile(file);
			}
              return true;
          }
          return super.onKeyDown(keyCode, event);
      }
	
	
	
	
	
}
